package cn.tedu.web.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import cn.tedu.web.entity.Goods;
import cn.tedu.web.entity.GoodsAddition;
import cn.tedu.web.entity.Image;
import cn.tedu.web.mapper.CategoryMapper;
import cn.tedu.web.mapper.GoodsAdditionMapper;
import cn.tedu.web.mapper.GoodsMapper;
import cn.tedu.web.mapper.ImageMapper;
import cn.tedu.web.service.IGoodsAdditionService;
import cn.tedu.web.service.IGoodsService;
import cn.tedu.web.service.IImageService;
import cn.tedu.web.utils.FileUtil;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author issen
 * @since 2021-09-24
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private GoodsAdditionMapper goodsAdditionMapper;
    @Resource
    private IGoodsAdditionService goodsAdditionsService;
    @Resource
    private ImageMapper imageMapper;
    @Resource
    private IImageService imageService;
    @Resource
    private FileUtil fileUtil;

    /**
     * 保存商品
     */
    @Transactional
    public Integer saveGoods(Goods goods) {
        // 1. 检查入参
        if (goods == null) {
            // 商品信息不允许为空
            return -1;
        }
        if (StringUtils.isBlank(goods.getName())) {
            // 商品名称不允许为空
            return -2;
        }
        if (goods.getPrice() == null || goods.getPrice() <= 0) {
            // 商品价格必须是非零正数
            return -3;
        }

        // 2. 保存商品基础信息
        Integer affectRows = goodsMapper.insert(goods);
        // 3. 保存商品附加信息
        List<GoodsAddition> additions = goods.getAdditions();
        if (additions != null && !additions.isEmpty()) {
            for (GoodsAddition addition : additions) {
                addition.setGid(goods.getId());
            }
            affectRows += goodsMapper.addGoodsAddition(additions);
        }
        return affectRows;
    }

    /**
     * 读取数据库中的数据并组装成 前端 需要的数据格式
     * 
     * @param pageNum  当前页码
     * @param pageSize 显示页数
     */
    public IPage<Goods> listGoods(int pageNum, int pageSize) {
        // 设置需要返回到前端的数据行
        IPage<Goods> goodses = goodsMapper.selectPage(new Page<>(pageNum, pageSize), null);
        // 为商品的分类名称赋值

        for (Goods goods : goodses.getRecords()) {
            // 获取商品细节
            goods = listDetail(goods);
        }
        return goodses;
    }

    @Override
    @Transactional
    public Integer updateGoods(Goods goods) {
        
        Integer gid = goods.getId();
        // 图片处理
        List<Image> images = goods.getImages();
        // 当前还有图片存在
        if (!CollectionUtils.isEmpty(images)) {
            // 要删除的图片id列表
            List<Integer> ids = new ArrayList<>();
            for (Image image : images) {
                if (image.getId() != null) {
                    ids.add(image.getId());
                }
            }
            if (!ids.isEmpty()) {
                List<Image> delImages = imageMapper
                        .selectList(new QueryWrapper<Image>().eq("gid", goods.getId()).notIn("id", ids));
                // 数据库数据删除
                imageMapper.delete(new QueryWrapper<Image>().eq("gid", gid).notIn("id", ids));
                // 删除源文件
                for (Image image : delImages) {
                    fileUtil.DeleteFolder(image.getUrl());
                }
            } else {
                List<Image> delImages = imageMapper.selectList(new QueryWrapper<Image>().eq("gid", goods.getId()));
                // 数据库数据删除
                imageMapper.delete(new QueryWrapper<Image>().eq("gid", gid));
                // 删除源文件
                for (Image image : delImages) {
                    fileUtil.DeleteFolder(image.getUrl());
                }
            }
        // 删除存在的图片
        } else {
            List<Image> delImages = imageMapper.selectList(new QueryWrapper<Image>().eq("gid", goods.getId()));
            // 数据库数据删除
            imageMapper.delete(new QueryWrapper<Image>().eq("gid", gid));
            // 删除源文件
            for (Image image : delImages) {
                fileUtil.DeleteFolder(image.getUrl());
            }
            System.out.println("要删除的图片" + delImages);
        }
        // 更新商品附加信息(商品附加信息表)
        List<GoodsAddition> additions = goods.getAdditions();
        // 先删除
        goodsAdditionMapper.delete(new QueryWrapper<GoodsAddition>().eq("gid", gid));

        // 进行添加
        if (additions != null && !additions.isEmpty()) {
            for (GoodsAddition addition : additions) {
                addition.setGid(gid);
            }
            goodsAdditionsService.saveOrUpdateBatch(additions);
        }
        if (images != null && !images.isEmpty()) {
            for (Image image : images) {
                image.setGid(gid);
            }
            imageService.saveOrUpdateBatch(images);
        }
        // 对商品表更新(包括图片字段image,商品分类字段cid)
        Integer affectRows = goodsMapper.updateById(goods);
        return affectRows;
    }

    @Transactional
    public Integer deleteGoods(Goods goods) {
        // 先删除数据库数据
        Integer affectRows = goodsMapper.deleteById(goods.getId());
        Integer gid = goods.getId();
        // 删除商品的附加信息
        affectRows += goodsAdditionMapper.delete(new QueryWrapper<GoodsAddition>().eq("gid", goods.getId()));
        List<Image> images = goods.getImages();
        if (images != null) {
            // 要删除的图片id列表
            List<Integer> ids = new ArrayList<>();
            for (Image image : images) {
                ids.add(image.getId());
            }
            List<Image> delImages = imageMapper
                    .selectList(new QueryWrapper<Image>().eq("gid", goods.getId()).notIn("id", ids));
            // 数据库数据删除
            imageMapper.delete(new QueryWrapper<Image>().eq("gid", gid).notIn("id", ids));
            // 删除源文件
            for (Image image : delImages) {
                fileUtil.DeleteFolder(image.getUrl());
            }
        }
        return affectRows;
    }

    public Goods listDetail(Goods goods) {
        // 附加信息
        String name = categoryMapper.findNameById(goods.getCid());
        goods.setCategoryName(name);
        List<GoodsAddition> additions = goodsAdditionMapper
                .selectList(new QueryWrapper<GoodsAddition>().eq("gid", goods.getId()));
        goods.setAdditions(additions);
        List<Image> images = imageMapper.selectList(new QueryWrapper<Image>().eq("gid", goods.getId()));
        List<String> srcList = new ArrayList<String>();
        for (Image image : images) {
            srcList.add(image.getUrl());
        }
        goods.setImages(images);
        goods.setSrcList(srcList);
        return goods;
    }

}
